import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../store";
import { message as antdMessage } from "antd";
import { RouteRawState } from "../types";
import { useLocation, Navigate } from "react-router-dom";
import React, { useEffect } from "react";
import { getUserInfo } from "../service";
import {
  LoginQuitActionCreator,
  loginSuccessActionCreator,
} from "../store/user/userActions";

type PropsType = {
  route: RouteRawState;
};
const BeforeEachRoute: React.FC<PropsType> = ({ route }) => {
  const whiteList = ["/signin"];
  document.title = route.meta.title;
  const token = useSelector((state: RootState) => state.user.token);
  const role = useSelector((state: RootState) => state.user.role);
  const dispatch = useDispatch();
  const { pathname } = useLocation();
  if (token) {
    if (token && !role) {
      (async () => {
        const resp = await getUserInfo(token);
        const { code, data } = resp.data;
        if (code === 200) {
          dispatch(
            loginSuccessActionCreator({
              ...data,
              token,
            })
          );
        } else {
          dispatch(LoginQuitActionCreator());
        }
      })();
    }
    if (whiteList.includes(pathname)) {
      return <Navigate to="/"></Navigate>;
    } else {
      return <>{route.element}</>;
    }
  } else {
    if (whiteList.includes(pathname)) {
      return <>{route.element}</>;
    } else {
      antdMessage.warning("用户未登录, 请登录 !!!");
      return <Navigate to="/signin"></Navigate>;
    }
  }
};
export default BeforeEachRoute;
